<template>
    <div class="header">
        <div>
            <i v-if="hasBack" class="el-icon-back" @click="back"></i>
            <span style="font-size: 20px">{{name}}</span>
        </div>
        <div class="userName">
            <div>
                <p>欢迎您: {{ userInfo && userInfo.userName || '' }} </p>
            </div>
            <div style="line-height: 51px;color: rgb(193 182 182); margin-left: 15px;cursor: pointer;">
                <a @click="logout">退出</a>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, onMounted, defineComponent } from 'vue';
import { pathMap, localstorage } from '../utils/index';
import { useRouter } from 'vue-router';

export default defineComponent({
    name: 'Header',
    setup() {
        const router = useRouter();

        const state = reactive({
            name: '模块管理',
            userInfo: { userName: '' },
            hasBack: false
        });

        onMounted(() => {
            const pathName = window.location.hash.split('/')[1] || '';
            if (pathName != 'login') {
                const userInfo = { userName: localstorage.get('userName') || '' };
                state.userInfo = userInfo;
            }
        });

        const back = () => {
            router.back();
        };

        router.afterEach((to) => {
            state.name = pathMap[to.name as string];
        })

        const logout = () => {
            if (!localstorage.get('token')) {
                return;
            }

            localstorage.remove('token');
            localstorage.remove('userName');
            window.location.href = '/';
        }

        return {
            ...toRefs(state),
            back,
            logout
        }
    }
})
</script>

<style scoped>
.header {
    height: 50px;
    border-bottom: 1px solid #e9e9e9;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
}

.userName {
    font-size: 15px;
    display: flex;
    color: #409eff;
    justify-content: center;
}

.button {
    width: 60px;
    height: 50px;
}

.bread {
    line-height: 26px;
    margin-left: 12px;
}

</style>